﻿/**************************************************************
 *
 * 唯一标识：9b5ffe62-1b15-42ce-9f36-539511816351
 * 命名空间：Sgr.DataCategories.Controllers
 * 创建时间：2023/8/20 16:57:30
 * 机器名称：DESKTOP-S0D075D
 * 创建者：antho
 * 电子邮箱：fengqinhua2016@163.com
 * 描述：
 *
 **************************************************************/

using MediatR;
using Microsoft.AspNetCore.Mvc;
using Sgr.Application.ViewModels;
using Sgr.AspNetCore.ActionFilters.AuditLogs;
using Sgr.AspNetCore.ActionFilters.Permissions;
using Sgr.DataCategories.Application.Commands.AdministrativeDivisions;
using Sgr.DataCategories.Application.Queries;
using Sgr.DataCategories.Application.ViewModels;

namespace Sgr.DataCategories.Controllers
{
    /// <summary>
    /// 行政区划管理接口
    /// </summary>
    [Route("api/v1/sgr/administrative-divisions")]
    [ApiController]
    [Produces("application/json")]
    [Tags("AdministrativeDivision")]
    public class AdministrativeDivisionController : ControllerBase
    {
        private readonly IMediator _mediator;
        private readonly IAdministrativeDivisionQueries _administrativeDivisionQueries;

        public AdministrativeDivisionController(IMediator mediator,
            IAdministrativeDivisionQueries administrativeDivisionQueries)
        {
            _mediator = mediator ?? throw new ArgumentNullException(nameof(mediator));
            _administrativeDivisionQueries = administrativeDivisionQueries ?? throw new ArgumentNullException(nameof(administrativeDivisionQueries));
        }

        #region Commond

        /// <summary>
        /// 创建行政区划
        /// </summary>
        /// <param name="command">创建行政区划的请求参数</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <response code="200">创建成功</response>
        /// <response code="400">请求参数验证失败</response>
        /// <response code="401">未经授权的访问</response>
        [CheckPermission(Permissions.CreateAndUpdateAdministrativeDivision)]
        [HttpPost]
        [ProducesResponseType(typeof(bool), StatusCodes.Status200OK)]
        [AuditLogActionFilter("创建行政区划")]
        public async Task<ActionResult<bool>> CreateAsync([FromBody] CreateAdministrativeDivisionCommand command, CancellationToken cancellationToken)
        {
            var result = await _mediator.Send(command, cancellationToken);
            return !result.IsSuccess ? this.CustomBadRequest(result.Message) : Ok(result.Data);
        }

        /// <summary>
        /// 更新行政区划
        /// </summary>
        /// <param name="command">更新行政区划的请求参数</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <response code="200">更新成功</response>
        /// <response code="400">请求参数验证失败</response>
        /// <response code="401">未经授权的访问</response>
        [CheckPermission(Permissions.CreateAndUpdateAdministrativeDivision)]
        [HttpPut]
        [ProducesResponseType(typeof(bool), StatusCodes.Status200OK)]
        [AuditLogActionFilter("修改行政区划")]
        public async Task<ActionResult<bool>> UpdateAsync([FromBody] UpdateAdministrativeDivisionCommand command, CancellationToken cancellationToken)
        {
            var result = await _mediator.Send(command, cancellationToken);
            return !result.IsSuccess ? this.CustomBadRequest(result.Message) : Ok(result.Data);
        }

        /// <summary>
        /// 删除行政区划
        /// </summary>
        /// <param name="id">要删除的行政区划ID</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <response code="200">删除成功</response>
        /// <response code="401">未经授权的访问</response>
        [CheckPermission(Permissions.DeleteAdministrativeDivision)]
        [HttpDelete("{id:long:min(1)}")]
        [ProducesResponseType(typeof(bool), StatusCodes.Status200OK)]
        [AuditLogActionFilter("删除行政区划")]
        public async Task<ActionResult<bool>> DeleteAsync([FromRoute] long id, CancellationToken cancellationToken)
        {
            var result = await _mediator.Send(new DeleteAdministrativeDivisionCommand { Id = id, IsCascade = true }, cancellationToken);
            return !result.IsSuccess ? this.CustomBadRequest(result.Message) : Ok(result.Data);
        }

        #endregion Commond

        #region Queries

        /// <summary>
        /// 分页查询行政区划列表
        /// </summary>
        /// <param name="request">查询条件</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <response code="200">查询成功</response>
        /// <response code="401">未经授权的访问</response>
        [CheckPermission(Permissions.QueryAdministrativeDivision)]
        [HttpPost("search")]
        [ProducesResponseType(typeof(PagedResponse<OutAdministrativeDivisionViewModel>), StatusCodes.Status200OK)]
        [AuditLogActionFilter("查询符合条件的行政区划集合")]
        public async Task<ActionResult<PagedResponse<OutAdministrativeDivisionViewModel>>> SearchAsync([FromBody] InAdministrativeDivisionSearchModel request, CancellationToken cancellationToken)
        {
            return Ok(await _administrativeDivisionQueries.GetPagedListAsync(request, cancellationToken));
        }

        /// <summary>
        /// 获取行政区划详情
        /// </summary>
        /// <param name="id">行政区划ID</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <response code="200">获取成功</response>
        /// <response code="401">未经授权的访问</response>
        /// <response code="404">指定的行政区划不存在</response>
        [CheckPermission(Permissions.QueryAdministrativeDivision)]
        [HttpGet("{id:long:min(1)}")]
        [ProducesResponseType(typeof(OutAdministrativeDivisionViewModel), StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        [AuditLogActionFilter("查询行政区划详情")]
        public async Task<ActionResult<OutAdministrativeDivisionViewModel>> GetAsync([FromRoute] long id, CancellationToken cancellationToken)
        {
            var item = await _administrativeDivisionQueries.GetByIdAsync(id, cancellationToken);
            return item == null ? NotFound() : Ok(item);
        }

        ///// <summary>
        ///// 获取行政区划树形结构
        ///// </summary>
        ///// <response code="200">获取成功</response>
        ///// <response code="401">未经授权的访问</response>
        //[HttpGet("treelist")]
        //[ProducesResponseType(typeof(IList<NameValue>), StatusCodes.Status200OK)]
        //[AuditLogActionFilter("查询行政区划树形结构")]
        //public async Task<ActionResult<IList<NameValue>>> GetTreeListAsync()
        //{
        //    //权限认证
        //    if (!await _authorizationService.AuthorizeAsync(User, Permissions.QueryAdministrativeDivision))
        //                 return Unauthorized();

        //    // 获取所有行政区划数据
        //    var items = await _administrativeDivisionQueries.GetItemsAsync();

        //    // 由于 NameValue 已经包含了 ParentValue 属性，可以直接返回
        //    // 前端可以根据 Value 和 ParentValue 的关系构建树形结构
        //    return Ok(items);
        //}

        /// <summary>
        /// 获取指定父级下的行政区划列表
        /// </summary>
        /// <param name="parentId">父级行政区划ID</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <response code="200">获取成功</response>
        /// <response code="401">未经授权的访问</response>
        [CheckPermission(Permissions.QueryAdministrativeDivision)]
        [HttpGet("list/{parentId:long}")]
        [ProducesResponseType(typeof(IEnumerable<OutAdministrativeDivisionViewModel>), StatusCodes.Status200OK)]
        [AuditLogActionFilter("查询指定父级下的行政区划列表")]
        public async Task<ActionResult<IEnumerable<OutAdministrativeDivisionViewModel>>> GetListByParentIdAsync(
            [FromRoute] long parentId,
            CancellationToken cancellationToken = default)
        {
            var items = await _administrativeDivisionQueries.GetListAsync(parentId, cancellationToken);
            return Ok(items);
        }

        #endregion Queries
    }
}